package alt.fr.ma.np.activities;

import java.util.ArrayList;

import alt.fr.ma.np.R;
import alt.fr.ma.np.soap.Parameter;
import alt.fr.ma.np.soap.SOAPRequest;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;

public class FaceBookActivity extends Activity {

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();
		switch (display.getRotation()) {
		case Surface.ROTATION_0:
			setContentView(R.layout.facebook);
			break;
		case Surface.ROTATION_90:
			setContentView(R.layout.facebook_landscape);
			break;
		case Surface.ROTATION_180:
			break;
		case Surface.ROTATION_270:
			break;
		}
	}

	/**
	 * Action for refreshContacts button
	 * 
	 * @param view
	 */
	public void refreshContactsAction(View view) {
		switch (view.getId()) {
		case R.id.refreshContacts:
			try {
				String result = getContacts();
				addContactsToDB(result);
				view.invalidate();
			} catch (InterruptedException e) {
				Log.d("ERROR - FaceBookActivity", "InterruptedException", e);
			}
			break;
		}
	}

	public String getContacts() throws InterruptedException {
		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(this);

		String login = preferences.getString("login", null);
		String password = preferences.getString("password", null);

		ArrayList<Parameter> params = new ArrayList<Parameter>();
		Parameter action = new Parameter("sAction", "FetchContacts");
		Parameter actionParams = new Parameter("sParams", "");
		params.add(action);
		params.add(actionParams);

		SOAPRequest SOAPRequest = new SOAPRequest("sociablon", login, password,
				"WSSociablonWebService", params);

		Thread request = new Thread(SOAPRequest);
		request.start();
		request.join();

		String response = "";
		try {
			response = SOAPRequest.getSOAPResponse();
		} catch (Exception e) {
			Log.d("ERROR - FaceBookActivity", "SOAPResponseException", e);
		}

		return response;
	}

	public void addContactsToDB(String contacts) {

	}
}
